package com.xf.system.utils.cloudApi.ali;

import cn.hutool.json.JSONUtil;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * @author xiefengf
 * @version 1.0
 * @date 2024/8/12 14:30
 */
@Component
public class AliApiUtils {

//    @Value("${ali.accessKey}")
    private String accessKey = "2****************************";

//    @Value("${ali.accessKeySecret}")
    private String accessKeySecret = "2****************************";

//    @Value("${ali.sms.signName}")
    private String signName = "阿里云短信测试";

//    @Value("${ali.sms.templateCode}")
    private String templateCode = "SMS_154950";

    /**
     * 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html。
     * Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
     * @throws Exception
     */
    public com.aliyun.dysmsapi20170525.Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId(accessKey)
                .setAccessKeySecret(accessKeySecret);
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    /**
     * 阿里云发送短信
     * @param phoneNumbers 手机号
     * @param smsCode 验证码
     * https://api.aliyun.com/api/Dysmsapi/2017-05-25/SendSms?spm=a2c4g.11186623.0.0.146f5ee7WLlmsD&RegionId=cn-zhangjiakou&tab=DOC&lang=JAVA&params={%22PhoneNumbers%22:%221390000****%22,%22SignName%22:%22%E9%98%BF%E9%87%8C%E4%BA%91%22,%22TemplateCode%22:%22SMS_15305****%22,%22TemplateParam%22:%22%7B%5C%22name%5C%22%3A%5C%22%E5%BC%A0%E4%B8%89%5C%22%2C%5C%22number%5C%22%3A%5C%221390000****%5C%22%7D%22}
     */
    public void aliSendSms(String phoneNumbers,String smsCode) {
        HashMap<String, String> paramMap = new HashMap<>();
        paramMap.put("code", smsCode);
        try {
            com.aliyun.dysmsapi20170525.Client client = createClient();
            com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                    .setPhoneNumbers(phoneNumbers)
                    .setSignName(signName)
                    .setTemplateCode(templateCode)
                    .setTemplateParam(JSONUtil.toJsonStr(paramMap));
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
            SendSmsResponseBody body = client.sendSmsWithOptions(sendSmsRequest, runtime).getBody();
            if (!"OK".equals(body.getCode())) {
                throw new RuntimeException("发送短信失败"+body.getMessage());
            }
        }catch (Exception e) {
            throw new RuntimeException("发送短信失败"+e.getMessage());
        }
    }

}
